package astro

import (
	"fmt"
	"github.com/gocolly/colly"
	"github.com/gogf/gf/v2/encoding/gjson"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/gtime"
	"github.com/gogf/gf/v2/text/gstr"
	"strings"
	"time"
	"uni-crawl-frame/core"
	"uni-crawl-frame/db/mysql/model/entity"
	"uni-crawl-frame/service/crawl/replayservice"
	"uni-crawl-frame/utils/timeutil"
)

type AstroCrawl struct {
	*core.AbstractCrawlReplayUrl
}

func (receiver *AstroCrawl) CreateProgram(replayConfig *entity.CmsCrawlReplayConfig, manifestTask *entity.CmsCrawlReplayManifestTask) {

	log := g.Log().Line()

	idx := strings.LastIndex(replayConfig.SeedUrl, "-") + 1
	jsonURL := fmt.Sprintf("https://contenthub-api.eco.astro.com.my/channel/%s.json", gstr.SubStr(replayConfig.SeedUrl, idx))
	log.Info(gctx.GetInitCtx(), "请求节目单API: ", jsonURL)

	coll := colly.NewCollector()
	coll.OnResponse(func(response *colly.Response) {
		//处理返回的节目
		jsonObj := gjson.New(response.Body)
		jsonArray := jsonObj.GetJsons(fmt.Sprintf("response.schedule.%s", manifestTask.ReplayDay))
		if len(jsonArray) == 0 {
			log.Info(gctx.GetInitCtx(), "未获取到节目单: ", replayConfig.SeedUrl)
			return
		}

		title := jsonObj.Get("response.title").String()
		category := jsonObj.Get("response.category").String()
		log.Info(gctx.GetInitCtx(), "生成节目单. title = ", title, ", category = ", category)
		for _, programJson := range jsonArray {

			programTask := new(entity.CmsCrawlReplayProgramTask)
			programTask.ConfigId = replayConfig.Id
			programTask.ManifestId = manifestTask.Id
			programTask.ProgramNo = programJson.Get("eventId").String()
			programTask.ProgramName = programJson.Get("title").String()
			programTask.CrawlStatus = replayservice.ProgramTaskInit
			programTask.ProgramStartTime = programJson.Get("datetime").GTime()
			programTask.HostIp = replayConfig.Host
			duration := programJson.Get("duration", timeutil.HH_MM_SS).Time()
			sec := duration.Hour()*60*60 + duration.Minute()*60 + duration.Second()
			programTask.ProgramEndTime = programTask.ProgramStartTime.Add(gtime.S * time.Duration(sec))
			programTask.CreateTime = gtime.Now()

			replayservice.CheckAndSave(programTask)
		}
	})

	_ = coll.Visit(jsonURL)
}
